package com.test1.administrator.website;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by Administrator on 2017/5/27.
 */

public class ClientService extends Service {

    //    线程池对象
    private ExecutorService mExecutors=null;
//    Client对象
    Client mClient=null;
    Handler outHandler;
    Message msgS=Message.obtain();
    ClientThread clientThread=new ClientThread();
    public static final int HOSTNAME=1;
    public static final int CLIENTHANDLERPREPERED=2;
    public static final int SENDMES=3;

    /**
     * Return the communication channel to the service.  May return null if
     * clients can not bind to the service.  The returned
     * {@link IBinder} is usually for a complex interface
     * that has been <a href="{@docRoot}guide/components/aidl.html">described using
     * aidl</a>.
     * <p>
     * <p><em>Note that unlike other application components, calls on to the
     * IBinder interface returned here may not happen on the main thread
     * of the process</em>.  More information about the main thread can be found in
     * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html">Processes and
     * Threads</a>.</p>
     *
     * @param intent The Intent that was used to bind to this service,
     *               as given to {@link Context#bindService
     *               Context.bindService}.  Note that any extras that were included with
     *               the Intent at that point will <em>not</em> be seen here.
     * @return Return an IBinder through which clients can call on to the
     * service.
     */
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {

        String hostName=intent.getStringExtra("hostName");

        clientThread.start();
//        handler 发送
        msgS.what=HOSTNAME;
        msgS.obj=hostName;
//        Log.v("clientThread","main____________________________"+clientThread.toString());


        outHandler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what){
                    case CLIENTHANDLERPREPERED:
//                        客户端handler 已准备就绪 调用客户端handler
                        clientThread.curHandler.sendMessage(msgS);

                }
            }
        };


//            创建线程池
        mExecutors= Executors.newCachedThreadPool();
//            启动一个线程用以守候从客户端发来的消息

//        new Thread(){
//
//            String hostName="";
//
//            @Override
//            public void run() {
//                Log.v("Thread-------","start");
//                Looper.prepare();
////                通过handler获得hostName
////            handler 接收hostName
//                curHandler=new Handler(){
//                    @Override
//                    public void handleMessage(Message msg) {
//                        switch (msg.what){
//                            case HOSTNAME:
//                                hostName=(String)msg.obj;
//                                Log.v("hostname--handler","handler  get  hostname ----------"+hostName);
//                        }
//                    }
//                };
//                Looper.loop();
//
//                mClient=new Client(hostName);
//                mExecutors.execute(mClient);
//            }
//        }.start();

        return new ServiceBinder();
    }
    public void sendMessage(String message){
        Message msgM=Message.obtain();
        msgM.what=SENDMES;
        msgM.obj=message;
        clientThread.curHandler.sendMessage(msgM);
    }

    class ClientThread extends Thread {
        String hostName="";
        Handler curHandler;
        @Override
        public void run() {
            Looper.prepare();
//            Log.v("ClientThrea","-------------------------Start");
//                通过handler获得hostName
//            handler 接收hostName
            curHandler=new Handler(){
                @Override
                public void handleMessage(Message msg) {
                    switch (msg.what){
                        case HOSTNAME:
                            hostName=(String)msg.obj;
                            Log.v("hostname--handler","handler  get  hostname ----------"+hostName);
                            mClient=new Client(hostName);
                            mExecutors.execute(mClient);
                            break;
                        case SENDMES:
                            mClient.sendMessage("SendWebSite#"+msg.obj.toString());
                            break;
                    }
                }
            };
//            Log.v("new Handke","ClientThread____________________________"+curHandler.toString());
            Message prepered=new Message();
            prepered.what=CLIENTHANDLERPREPERED;
            outHandler.sendMessage(prepered);
            Looper.loop();


        }
    }

    class Client implements Runnable{
//        Socket clientSocket=null;
        Socket clientSocket;

        int port=6259;
        String hostname;
        String message="";
        PrintWriter out=null;
        BufferedReader in;

        public Client(String hostname){
            this.hostname=hostname;
            SocketAddress socketAddress=new InetSocketAddress(hostname,port);
                    try {
//                连接服务器 10s超时
                        clientSocket=new Socket(hostname,port);
                        if(!clientSocket.isConnected())
                        clientSocket.connect(socketAddress,10000);
                        in=new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                        out=new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(clientSocket.getOutputStream())));
                        sendMessage("------------first message!!!!!!!!!!");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }


        }

        public void sendMessage(String message){
            message=message+"\n";
            out.print(message);
            out.flush();
        }

        /**
         * When an object implementing interface <code>Runnable</code> is used
         * to create a thread, starting the thread causes the object's
         * <code>run</code> method to be called in that separately executing
         * thread.
         * <p>
         * The general contract of the method <code>run</code> is that it may
         * take any action whatsoever.
         *
         * @see Thread#run()
         */
        @Override
        public void run() {
            while(true){
//                Log.v("client","=====================client 运行中");
//                sendMessage("=========================first message!!!!!!!!!!");
                try {
                    message=null;
                    if((message=in.readLine())!=null){
                        Log.e("clientmessage",message);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    class ServiceBinder extends Binder {
        public ClientService getService(){
            return ClientService.this;
        }
    }
}
